<template>
  <div class="tenant-detail">
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="basic">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="租户编码">{{ tenantInfo.tenantCode }}</el-descriptions-item>
          <el-descriptions-item label="租户名称">{{ tenantInfo.tenantName }}</el-descriptions-item>
          <el-descriptions-item label="租户类型">
            <el-tag :type="getTenantTypeTag(tenantInfo.tenantType)">
              {{ getTenantTypeName(tenantInfo.tenantType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="租户状态">
            <el-tag :type="getStatusTag(tenantInfo.status)">
              {{ tenantInfo.statusName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="租户域名">{{ tenantInfo.domain || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="联系人姓名">{{ tenantInfo.contactName }}</el-descriptions-item>
          <el-descriptions-item label="联系人电话">{{ tenantInfo.contactPhone || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="联系人邮箱">{{ tenantInfo.contactEmail }}</el-descriptions-item>
          <el-descriptions-item label="租户地址" :span="2">{{ tenantInfo.address || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ parseTime(tenantInfo.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ parseTime(tenantInfo.updateTime) }}</el-descriptions-item>
          <el-descriptions-item label="到期时间">
            <span v-if="tenantInfo.expireTime">{{ parseTime(tenantInfo.expireTime) }}</span>
            <span v-else>永久</span>
            <el-tag v-if="tenantInfo.isExpiringSoon" type="warning" size="small" class="ml-2">即将到期</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="剩余天数">
            <span v-if="tenantInfo.remainingDays !== null">{{ tenantInfo.remainingDays }}天</span>
            <span v-else>永久</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>

      <!-- 资源使用情况 -->
      <el-tab-pane label="资源使用" name="resource">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="resource-card">
              <template #header>
                <div class="card-header">
                  <span>用户使用情况</span>
                </div>
              </template>
              <div class="resource-content">
                <div class="resource-progress">
                  <el-progress 
                    type="circle" 
                    :percentage="getUserUsageRate()" 
                    :color="getUsageColor(getUserUsageRate())"
                    :width="120"
                  >
                    <template #default="{ percentage }">
                      <span class="percentage-value">{{ percentage }}%</span>
                    </template>
                  </el-progress>
                </div>
                <div class="resource-info">
                  <p>当前用户数：{{ tenantInfo.currentUsers }}</p>
                  <p>最大用户数：{{ tenantInfo.maxUsers }}</p>
                  <p>可用用户数：{{ tenantInfo.maxUsers - tenantInfo.currentUsers }}</p>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="resource-card">
              <template #header>
                <div class="card-header">
                  <span>存储使用情况</span>
                </div>
              </template>
              <div class="resource-content">
                <div class="resource-progress">
                  <el-progress 
                    type="circle" 
                    :percentage="tenantInfo.storageUsageRate || 0" 
                    :color="getUsageColor(tenantInfo.storageUsageRate || 0)"
                    :width="120"
                  >
                    <template #default="{ percentage }">
                      <span class="percentage-value">{{ percentage }}%</span>
                    </template>
                  </el-progress>
                </div>
                <div class="resource-info">
                  <p>已用存储：{{ tenantInfo.storageUsedFormatted }}</p>
                  <p>总存储：{{ tenantInfo.storageQuotaFormatted }}</p>
                  <p>可用存储：{{ getAvailableStorage() }}</p>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 统计信息 -->
      <el-tab-pane label="统计信息" name="stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="总用户数" :value="tenantInfo.currentUsers" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="活跃用户数" :value="statsInfo.activeUsers || 0" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="今日登录" :value="statsInfo.todayLogins || 0" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="本月新增" :value="statsInfo.monthlyNewUsers || 0" />
          </el-col>
        </el-row>
        
        <el-divider />
        
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="存储使用率" :value="tenantInfo.storageUsageRate || 0" suffix="%" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="用户使用率" :value="getUserUsageRate()" suffix="%" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="剩余天数" :value="tenantInfo.remainingDays || 0" suffix="天" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="创建天数" :value="getCreatedDays()" suffix="天" />
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 操作日志 -->
      <el-tab-pane label="操作日志" name="logs">
        <el-table :data="operationLogs" v-loading="logsLoading">
          <el-table-column label="操作时间" prop="createTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作用户" prop="username" width="120" />
          <el-table-column label="操作类型" prop="operationType" width="120">
            <template #default="scope">
              <el-tag :type="getOperationTypeTag(scope.row.operationType)">
                {{ scope.row.operationType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作描述" prop="description" :show-overflow-tooltip="true" />
          <el-table-column label="IP地址" prop="ipAddress" width="140" />
          <el-table-column label="用户代理" prop="userAgent" :show-overflow-tooltip="true" />
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="logParams.pageNum"
            v-model:page-size="logParams.pageSize"
            :total="logTotal"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="getOperationLogs"
            @current-change="getOperationLogs"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { parseTime } from '@/utils'
import { 
  getTenantDetail, 
  getTenantUserStats, 
  getTenantOperationLogs 
} from '@/api/tenant'

// Props
const props = defineProps({
  tenantId: {
    type: String,
    required: true
  }
})

// Emits
const emit = defineEmits(['close'])

// 响应式数据
const activeTab = ref('basic')
const loading = ref(true)
const logsLoading = ref(false)
const tenantInfo = ref({})
const statsInfo = ref({})
const operationLogs = ref([])
const logTotal = ref(0)

// 日志查询参数
const logParams = reactive({
  pageNum: 1,
  pageSize: 10
})

// 获取租户详情
const getTenantInfo = async () => {
  try {
    loading.value = true
    const response = await getTenantDetail(props.tenantId)
    tenantInfo.value = response.data
  } catch (error) {
    ElMessage.error('获取租户详情失败')
  } finally {
    loading.value = false
  }
}

// 获取统计信息
const getStatsInfo = async () => {
  try {
    const response = await getTenantUserStats(props.tenantId)
    statsInfo.value = response.data
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 获取操作日志
const getOperationLogs = async () => {
  try {
    logsLoading.value = true
    const response = await getTenantOperationLogs(props.tenantId, logParams)
    operationLogs.value = response.data.records
    logTotal.value = response.data.total
  } catch (error) {
    console.error('获取操作日志失败:', error)
  } finally {
    logsLoading.value = false
  }
}

// 获取用户使用率
const getUserUsageRate = () => {
  if (!tenantInfo.value.maxUsers || tenantInfo.value.maxUsers === 0) return 0
  return Math.round((tenantInfo.value.currentUsers / tenantInfo.value.maxUsers) * 100)
}

// 获取可用存储
const getAvailableStorage = () => {
  const available = tenantInfo.value.storageQuota - tenantInfo.value.storageUsed
  return formatFileSize(available)
}

// 获取创建天数
const getCreatedDays = () => {
  if (!tenantInfo.value.createTime) return 0
  const createDate = new Date(tenantInfo.value.createTime)
  const now = new Date()
  return Math.floor((now - createDate) / (1000 * 60 * 60 * 24))
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取租户类型名称
const getTenantTypeName = (type) => {
  const typeMap = {
    1: '企业版',
    2: '个人版',
    3: '试用版'
  }
  return typeMap[type] || '未知'
}

// 获取租户类型标签
const getTenantTypeTag = (type) => {
  const tagMap = {
    1: 'primary',
    2: 'success',
    3: 'warning'
  }
  return tagMap[type] || 'info'
}

// 获取状态标签
const getStatusTag = (status) => {
  const tagMap = {
    0: 'danger',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return tagMap[status] || 'info'
}

// 获取使用率颜色
const getUsageColor = (rate) => {
  if (rate >= 90) return '#f56c6c'
  if (rate >= 70) return '#e6a23c'
  return '#67c23a'
}

// 获取操作类型标签
const getOperationTypeTag = (type) => {
  const tagMap = {
    'CREATE': 'success',
    'UPDATE': 'primary',
    'DELETE': 'danger',
    'LOGIN': 'info',
    'LOGOUT': 'warning'
  }
  return tagMap[type] || 'info'
}

// 组件挂载时获取数据
onMounted(() => {
  getTenantInfo()
  getStatsInfo()
  getOperationLogs()
})
</script>

<style lang="scss" scoped>
.tenant-detail {
  .resource-card {
    height: 280px;
    
    .card-header {
      font-weight: 500;
    }
    
    .resource-content {
      display: flex;
      align-items: center;
      height: 200px;
      
      .resource-progress {
        flex: 1;
        display: flex;
        justify-content: center;
        
        .percentage-value {
          font-size: 16px;
          font-weight: 500;
        }
      }
      
      .resource-info {
        flex: 1;
        padding-left: 20px;
        
        p {
          margin: 8px 0;
          font-size: 14px;
          color: #606266;
        }
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  
  .ml-2 {
    margin-left: 8px;
  }
}

:deep(.el-descriptions__label) {
  font-weight: 500;
}

:deep(.el-statistic__content) {
  text-align: center;
}
</style>
